// Copyright 2011 Jefferson Willian
// willmont7@gmail.com

#include <cstdio>

#define MAX 12

#define INF 10000000

int moves[4][2] = {-1,  0,
                    0, -1,
                    1,  0,
                    0,  1};

/* Resolve o problema - backtracking */
void solve(int bcktrck[][MAX], int in[][MAX], int xy[]) {
  int newXY[2];
  /* Realiza os quatro movimentos possiveis */
  for (int i = 0;i < 4;i++) {
    int mx = moves[i][0];
    int my = moves[i][1];
    /* Verifica se o movimento eh valido */
    if (in[xy[0]+mx][xy[1]+my] == 1 || in[xy[0]+mx][xy[1]+my] == 0)
      /* Verifica se o movimento eh melhor que o estado anterior */
      if (bcktrck[xy[0]][xy[1]] + 1 < bcktrck[xy[0]+mx][xy[1]+my]) {
        bcktrck[xy[0]+mx][xy[1]+my] = bcktrck[xy[0]][xy[1]] + 1;
        newXY[0] = xy[0] + mx;
        newXY[1] = xy[1] + my;
        solve(bcktrck, in, newXY);
      }
  }

  return;
}

int main() {
  int in[MAX][MAX];       // Matriz de entrada
  int bcktrck[MAX][MAX];  // Matriz de processo do backtracking
  int init[2];            // Coordenadas iniciais
  int ret = INF;
  int n, m;
  int i, j;

  scanf("%d%d", &n, &m);

  for (int i = 1;i <= n;i++)
    for (int j = 1;j <= m;j++) {
      bcktrck[i][j] = INF;
      scanf("%d", &in[i][j]);
      if (in[i][j] == 3) {
        init[0] = i;
        init[1] = j;
      }
    }

  /* bcktrck -> 0 -> saida          */
  /*         -> 1 -> caminho livre  */
  /*         -> 2 -> parede         */

  /* Coloca paredes ao redor da matriz */
  for (int i = 0;i <= n+1;i++) {
    in[i][0] = 2;
    in[i][m+1] = 2;
  }
  for (int i = 0;i <= m+1;i++) {
    in[0][i] = 2;
    in[n+1][i] = 2;
  }

  /* Estado inicial */
  bcktrck[init[0]][init[1]] = 0;

  solve(bcktrck, in, init);

  for (int i = 1;i <= n;i++)
    for (int j = 1;j <= m;j++)
      if (in[i][j] == 0 && bcktrck[i][j] < ret)
        ret = bcktrck[i][j];

  printf("%d\n", ret);

  return 0;
}
